import waterfall from 'async/waterfall'
import trim from 'lodash/trim'
import isArray from 'lodash/isArray'
//必须带done回调 执行完成调用
export default function dblClickTableRow({ vm, action, done, callbackData, additionalData }) {
  let tableIds = action.extension.tableId.value

  console.log('双击 tableIds', tableIds, callbackData)

  let _task = []
  isArray(tableIds) &&
    tableIds.forEach((tableId) => {
      let _rowNumber = 0
      if (tableId) {
        let _table = vm.vuiComponents[tableId]

        if (_table) {
          //new code
          if (action.extension.selectRowType) {
            let selectRowType = action.extension.selectRowType.value
            if (selectRowType.type === '1') {
              //1固定下标
              _rowNumber = selectRowType.index
            } else if (selectRowType.type === '2') {
              //2动态获取
              let _rowData = {}
              if (selectRowType.key.indexOf(',') > -1) {
                // 如果有逗号拼接则为多条件匹配
                const keyList = selectRowType.key.split(',')
                _table.ref.getData().forEach((v) => {
                  let flag = true
                  keyList.forEach((keyItem) => {
                    // 如果有其中一个字段没匹配上则匹配失败
                    if (v[trim(keyItem)] != callbackData[trim(keyItem)]) {
                      flag = false
                    }
                  })
                  if (flag) {
                    _rowData = v
                  }
                })
              } else {
                let _value = callbackData[selectRowType.key] //获取上个任务返回的值
                _table.ref.getData().forEach((v) => {
                  if (v[selectRowType.key] == _value) {
                    _rowData = v
                  }
                })
              }

              _rowNumber = _table.ref.getRowIndex(_rowData)
            } else {
              let _rowData = additionalData || {}
              _rowNumber = _table.ref.getRowIndex(_rowData)
            }
          } else {
            //兼容旧配置
            _rowNumber = action.extension.rowNumber ? action.extension.rowNumber.value : 0
          }

          // 写入下标偏移量
          if (action.extension.indexOffset && action.extension.indexOffset.value) _rowNumber += action.extension.indexOffset.value

          let _info = _table.ref.getData(parseInt(_rowNumber))
          if (_info) {
            _task.push((cb) => {
              _table.self.cellDBLClickEvent({
                row: _info,
              })
              setTimeout(() => {
                cb()
              }, 10)
            })
          } else {
            console.log('没有找到对应row')
          }
        } else {
          console.log('手动触发表格点击-没有找到表格')
        }
      }
    })

  waterfall(_task, function (err, result) {
    console.log('完成 print', err, result)
    done(null, {})
  })
}
